package com.heima.media.listener;

import com.alibaba.fastjson.JSON;
import com.heima.media.entity.WmNews;
import com.heima.media.service.IAuditService;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class ArticlePublishListener {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private IAuditService auditService;

    @PostConstruct  // 实例化完成后自动执行该方法
    public void init() {
        // 通过线程开启任务监听
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 开启redisson延迟队列的监听
                // 创建阻塞队列
                RBlockingQueue<String> blockingQueue = redissonClient.getBlockingQueue("article_publish");

                // 开启监听时发送一条初始化消息
                // 创建延迟队列
                RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(blockingQueue);
                delayedQueue.offer("init", 1, TimeUnit.SECONDS);

                // 循环获取消息
                while (true) {
                    // 从队列拉取消息
                    try {
                        String msg = blockingQueue.poll(1, TimeUnit.MINUTES);
                        if (!StringUtils.isEmpty(msg) && !msg.equals("init")) {
                            System.out.println("接收到消息: " + msg + " " + new Date());
                            // 解析文章
                            WmNews wmNews = JSON.parseObject(msg, WmNews.class);
                            // 已经到了发布时间,需要将文章进行实际的发布
                            auditService.audit(wmNews);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();


    }
}
